/*
 * Copyright 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mycompany.controller.account;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.broadleafcommerce.common.exception.ServiceException;
import org.broadleafcommerce.common.service.GenericResponse;
import org.broadleafcommerce.core.web.controller.account.BroadleafLoginController;
import org.broadleafcommerce.core.web.controller.account.ResetPasswordForm;
import org.broadleafcommerce.profile.core.dao.CustomerDao;
import org.broadleafcommerce.profile.core.domain.Customer;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.mycompany.core.profile.domain.HCCustomerImpl;

/**
 * The controller responsible for all actions involving logging a customer in
 */
@Controller
public class LoginController extends BroadleafLoginController {

	@Resource(name="blCustomerDao")
	protected CustomerDao customerDao;

	@RequestMapping("/login")
	public String login(HttpServletRequest request, HttpServletResponse response, Model model) {


		return super.login(request, response, model);
	}

	@RequestMapping(value="/login/forgotPassword2", method=RequestMethod.GET)
	public String forgotPassword(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		return super.forgotPassword(request, response, model);

	}
	@RequestMapping(value="/login/forgotPassword3", method=RequestMethod.POST)
	public String processForgotPassword(@RequestParam("emailAddress") String emailAddress, HttpServletRequest request, Model model) {

		Customer customer = null;

		if (emailAddress != null) {

			//String s=request.getParameter(emailAddress);
			

			customer = customerDao.readCustomerByEmail(emailAddress);

			if(customer!=null){

				HCCustomerImpl hcCustomerImpl = (HCCustomerImpl)customer;
				String dbemailaddress=hcCustomerImpl.getEmailAddress();
				String dbquestion=hcCustomerImpl.getSecurityQuestion();


				dbemailaddress=hcCustomerImpl.getEmailAddress();
			

				return "redirect:securityQuestion2.html?emailAddress="+emailAddress+"&"+"securityQuestion="+dbquestion;

			}
			else{
				return "authentication/forgotPassword";
			}

		}
		//	return super.processForgotPassword(username, request, model)
		return null;
	}   

	@RequestMapping(value="/login/securityQuestion2" )
	public String showSecurityQuestion(@RequestParam("emailAddress") String emailAddress,@RequestParam("securityQuestion")String securityQuestion,HttpServletRequest req, @ModelAttribute("customizedFieldLoginUpdation") CustomizedFieldLoginUpdation form) {

		System.out.println(emailAddress);
		System.out.println(securityQuestion);
		form.setEmailAddress(emailAddress);

		form.setSecurityQuestion(securityQuestion);
		System.out.println("hellu");
		return "authentication/securityquestion";



	}

	@RequestMapping(value="/login/securityQuestion", method=RequestMethod.POST)
	public String processSecurityQuestion(@RequestParam("securityQuestion") String securityQuestion,@RequestParam("securityAnswer") String securityAnswer,@RequestParam("emailAddress") String emailAddress,HttpServletRequest request, Model model, @ModelAttribute("customizedFieldLoginUpdation") CustomizedFieldLoginUpdation form) {
		System.out.println(emailAddress);
		/*if(((HCCustomerImpl)model.asMap().get("customerDipu")).getSecurityAnswer().equalsIgnoreCase(securityAnswer)){
		 */	

		Customer customer;
		if (securityQuestion != null ) {

			//String s=request.getParameter(emailAddress);

			customer = customerDao.readCustomerByEmail(emailAddress);

			if(customer!=null){
				
				HCCustomerImpl hcCustomerImpl = (HCCustomerImpl)customer;
				String dbsecurityanswer=hcCustomerImpl.getSecurityAnswer();
				String dbquestion=hcCustomerImpl.getSecurityQuestion();

				if(securityQuestion.equalsIgnoreCase(dbquestion) && securityAnswer.equalsIgnoreCase(dbsecurityanswer)){

					GenericResponse errorResponse = customerService.sendForgotPasswordNotification(emailAddress, getResetPasswordUrl(request));
					if (errorResponse.getHasErrors()) {
						String errorCode = errorResponse.getErrorCodesList().get(0);
						model.addAttribute("errorCode", errorCode);             
						return getForgotPasswordView();
					} else {
						request.getSession(true).setAttribute("forgot_password_username", emailAddress);
						return getForgotPasswordSuccessView();
					}
				}
				else{
					return "redirect:securityQuestion2.html?emailAddress="+emailAddress+"&"+"securityQuestion="+dbquestion;
				}
					
			}
		}
		return null;

	}   
	@RequestMapping(value="/login/resetPassword", method=RequestMethod.GET)
	public String resetPassword(HttpServletRequest request, HttpServletResponse response, Model model) {
		return super.resetPassword(request, response, model);
	}   

	@RequestMapping(value="/login/resetPassword", method=RequestMethod.POST)
	public String processResetPassword(@ModelAttribute("resetPasswordForm") ResetPasswordForm resetPasswordForm, HttpServletRequest request, HttpServletResponse response, Model model, BindingResult errors) throws ServiceException {
		return super.processResetPassword(resetPasswordForm, request, response, model, errors);
	}   

	@Override
	public String getResetPasswordUrl(HttpServletRequest request) {     
		String url = request.getScheme() + "://" + request.getServerName() + getResetPasswordPort(request, request.getScheme() + "/");

		if (request.getContextPath() != null && ! "".equals(request.getContextPath())) {
			url = url + request.getContextPath()+ "/login/resetPassword";
		} else {
			url = url + "/login/resetPassword";
		}
		return url;
	}
}
